//
//  BusinessInfoViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/7/18.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "BusinessInfoViewController.h"
#import "BusinessInfoTableViewCell.h"
#import "BusinessInfoDetailViewController.h"
#import "BusinessInfoCollectionViewCell.h"
static NSString * cellIndentifier = @"BusinessInfoTableViewCell";
static NSString * CellIndentifier = @"BusinessInfoCollectionViewCell";
@interface BusinessInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *headTitle;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property(nonatomic,strong)NSArray * typeArray;
@property(nonatomic,strong)NSIndexPath * selectedPath;
@property(nonatomic,strong)NSMutableArray * newsArray;
@property(nonatomic,assign)CGFloat score;
@end

@implementation BusinessInfoViewController
- (void)viewWillAppear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self getPersonScore];
    [_tableView.header beginRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _newsArray = [NSMutableArray array];
    _pageNO = 1;
    _selectedPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self initviewLayout];
    
    [self GettypeList];
    // Do any additional setup after loading the view.
}

- (void)initviewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [_tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.collectionViewLayout = flowLayout;
    [self.collectionView registerNib:[UINib nibWithNibName:CellIndentifier bundle:nil] forCellWithReuseIdentifier:CellIndentifier];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;


}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark === 分类列表
- (void)GettypeList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryCategoryList withHttpType:@"POST" withTag:GS_GS_queryCategoryList];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getShopList];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.newsArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getShopList];
        });
    }
    
}

#pragma mark === 获取行业资讯列表
- (void)getShopList{

    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"page"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    [dic setObject:_typeArray[_selectedPath.row][@"acId"] forKey:@"categoryId"];
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryArticleList withHttpType:@"POST" withTag:GS_GS_queryArticleList];
}


#pragma mark ===  查询用户积分
- (void)getPersonScore{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    self.shareApi.delegate=self;
    
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryScoreInfo withHttpType:@"POST" withTag:GS_GS_queryScoreInfo];
}



#pragma mark  ==== tableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _newsArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 97*VerticalRatio();
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BusinessInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[BusinessInfoTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    NSDictionary * dic = _newsArray[indexPath.row];
    
    cell.newsTitle.text = [NSString stringWithFormat:@"%@",dic[@"ATitle"]];
    cell.newsScanNum.text = [NSString stringWithFormat:@"%@",dic[@"aReadTimes"]];
    cell.scanScore.text = [NSString stringWithFormat:@"%@",dic[@"aScore"]];
    cell.newsDate.text = [NSString stringWithFormat:@"%@",dic[@"APubdate"]];
    
    NSString * image =[NSString stringWithFormat:@"%@",dic[@"ATitleImagePath"]];
    if (image.length>0) {
        [cell.newsImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }
    
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    NSDictionary * dic = _newsArray[indexPath.row];
    
    NSInteger aIsScore = [dic[@"aIsScore"]integerValue];//1 不需积分  2需要
    NSInteger aIsExchange = [dic[@"aIsExchange"]integerValue];//1 已兑换  2未兑换
    CGFloat needScore = [dic[@"aScore"]floatValue];
    if (aIsScore == 1 ||(aIsScore==2&&aIsExchange == 1)) {
        UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        BusinessInfoDetailViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"BusinessInfoDetail"];
        page.newsId = [NSString stringWithFormat:@"%@",_newsArray[indexPath.row][@"AId"]];
        page.newsName = [NSString stringWithFormat:@"%@",_newsArray[indexPath.row][@"ATitle"]];
        [[Common getNavigation]pushViewController:page];
    }else if (aIsScore == 2 && aIsExchange == 2) {
        if (_score>needScore) {
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            BusinessInfoDetailViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"BusinessInfoDetail"];
            page.newsId = [NSString stringWithFormat:@"%@",_newsArray[indexPath.row][@"AId"]];
            page.newsName = [NSString stringWithFormat:@"%@",_newsArray[indexPath.row][@"ATitle"]];
            [[Common getNavigation]pushViewController:page];
        }else{
            UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"积分不足！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }
    }

}


#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _typeArray.count;
}
//定义展示的Section的个数
-(NSInteger)nmumberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(80*VerticalRatio(), 40*VerticalRatio());
   
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0,0, 0, 0);
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BusinessInfoCollectionViewCell * topCell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIndentifier forIndexPath:indexPath];
        topCell.backgroundColor = [UIColor clearColor];
    
    topCell.typeName.textColor = [UIColor colorWithWhite:0.325 alpha:1.000];
    if (indexPath.row == _selectedPath.row) {
        topCell.typeName.textColor = [UIColor colorWithRed:0.000 green:0.584 blue:0.867 alpha:1.000];
    }
    
    topCell.typeName.text = [NSString stringWithFormat:@"%@",_typeArray[indexPath.row][@"acCategoryName"]];
    
    UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(79, 11, 1, 18), NO)];
    line.backgroundColor= [UIColor colorWithWhite:0.922 alpha:1.000];
    if (indexPath.row<_typeArray.count-1) {
        [topCell addSubview:line];
    }
    return topCell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    _selectedPath = indexPath;
    [_collectionView reloadData];
    [_tableView.header beginRefreshing];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag == GS_GS_queryCategoryList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else{
            _typeArray =database[@"result"][@"list"];
            [_collectionView reloadData];
            [self addRefreshing];
        }
        
    }else if (tag==GS_GS_queryArticleList) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.newsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.newsArray addObject:entity];
                }
                
                [_tableView reloadData];
                
            });
            
        }
        
    }else if (tag == GS_GS_queryScoreInfo){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {

            _score = [[Common stringFromData:database[@"result"][@"museScore"]]floatValue];
        }
        
    }

   }
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    [self dismissWaitDialog];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
